<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Expression;

class ThemesSejourTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
    	$this->tableGateway = $tableGateway;
    }
    
    public function fetchAll( $sejourId )
    {
        $sql = new Sql($this->tableGateway->getAdapter());
        $select = $sql->select();

        $select->from($this->tableGateway->table)
            ->join('Thematiques', 'ThemesSejour.themeId = Thematiques.themeId', array('themeLibelle'), 'inner')
            ->where->equalTo('ThemesSejour.sejourId', $sejourId);
        
        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        return $resultSet;
    }

    public function fetchAllArray( $sejourId )
    {
        $resultSet = $this->fetchAll( $sejourId );
        $entities = array();
        
        foreach ($resultSet as $row) {
        	$obj = new ThemesSejour();
        	$obj->exchangeArray( (array) $row);
        	$entities[] = $obj;
        }
        
        return $entities;
    }

    public function insererThematiquesSejour( $sejour ) {
        $data = array();

        $sejourId = $sejour->id;

        $data['sejourId'] = $sejourId;

        $thematiques = $sejour->thematiques;

        foreach ($thematiques as $key => $themeId) {

            $data['themeId'] = $themeId;

            $this->tableGateway->insert($data);
        }
    }

    public function mettreAJourThematiquesSejour( $sejour ) {
        $this->retirerThematiquesSejour( $sejour->id );

        $this->insererThematiquesSejour($sejour);
    }

    public function retirerThematiquesSejour( $sejourId )
    {
        $this->tableGateway->delete(array('sejourId' => $sejourId));
    }

    public function tousLesSejoursAvecThemesNonActifs()
    {
        $sql = new Sql($this->tableGateway->getAdapter());
        $select = $sql->select();

        $select->from($this->tableGateway->table)
            ->join('Thematiques', 'ThemesSejour.themeId = Thematiques.themeId', array(), 'inner')
            ->where->equalTo('Thematiques.active', "0");//thematique non active
        
        $statement = $sql->prepareStatementForSqlObject($select);
        $resultSet = $statement->execute();

        return $resultSet;
    }

}